package com.java.base.exercise;

import com.alibaba.fastjson.JSON;
import com.java.base.exercise.current.TwinsLock;
import com.java.base.exercise.designmode.beiwangmoshi.Admin;
import com.java.base.exercise.designmode.beiwangmoshi.ConfigFile;
import com.java.base.exercise.designmode.beiwangmoshi.ConfigOriginator;
import com.java.base.exercise.factory.DistributeSimpleFactory;
import com.java.base.exercise.factory.StateType;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * @Author:RenPu
 * @Date: 2020/10/29 18:47
 * @Version: 1.0
 * @description: java基础的练习
 */
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {JavaBaseApplication.class})
public class JavaBaseExercise {


    @Resource
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private DistributeSimpleFactory distributeSimpleFactory;



    //测试linkhashmap，put顺序以及访问顺序
    @Test
    public void linkHashMapTest() {
        Map<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("name1", "josan1");
        linkedHashMap.put("name2", "josan2");
        linkedHashMap.put("name3", "josan3");
        Set<Map.Entry<String, String>> set = linkedHashMap.entrySet();
        Iterator<Map.Entry<String, String>> iterator = set.iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = iterator.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            System.out.println("key:" + key + ",value:" + value);
        }
    }


    @Test
    public void insertDataBase() {
        for (int i = 0; i < 10000; i++) {
            jdbcTemplate.execute("insert into studentes_two(name,grade,progress) values('888','000','111')");

            //jdbcTemplate.execute("insert into studentes(name,grade,progress) values('888','000','111')");


        }
    }


    //测试hashmap的扩容机制以及，数据结构的转变
    @Test
    public void hashMapTest() {

        HashMap<String, Integer> map = new HashMap<>();

        int t = 0;
        for (int i = 0; i < 16; i++) {

            t++;
            map.put("key" + t, t + 1);

        }

    }


    //根据集合里的某个属性，进行排序
    @Test
    public void sortColleation() {


        //使用var省略，写对象的类型

        var People1 = new People("老张", 3);
        var People2 = new People("老李", 1);
        var People3 = new People("老王", 2);
        List<People> list = new ArrayList<>();
        list.add(People1);
        list.add(People2);
        list.add(People3);


        System.out.println("排序前--:" + list.toString());
        Collections.sort(list, new Comparator<People>() {
            @Override
            public int compare(People o1, People o2) {
                //升序
                return o1.getAge().compareTo(o2.getAge());
            }
        });


        System.out.println("升序排序后--:" + list.toString());

        Collections.sort(list, new Comparator<People>() {
            @Override
            public int compare(People o1, People o2) {
                //降序
                return o2.getAge().compareTo(o1.getAge());
            }
        });


        System.out.println("降序排序后--:" + list.toString());
    }


    @Test
    public void testSetImplement() {

        // 三者都不是线程安全的，如果要使用线程安全可以Collections.synchronizedSet()
        // HashSet插入数据最快，其次LinkHashSet，最慢的是TreeSet因为内部实现排序

        //插入数据较快，当不知道使用什么类型的Set，默认可以使用这个
        HashSet<String> hashSet = new HashSet<>();

        //保证插入入的数据，会按照插入的顺序，进行获取（FIFO 先进先出）
        LinkedHashSet<String> linkHashSet = new LinkedHashSet<>();

        //TreeSet的主要功能用于排序
        TreeSet<String> treeSet = new TreeSet<>();

        for (String data : Arrays.asList("D", "E", "W", "C", "A")) {

            hashSet.add(data);

            linkHashSet.add(data);

            treeSet.add(data);
        }


        //不保证有序
        System.out.println("hashSet-------:" + hashSet);

        //FIFO保证安装插入顺序排序
        System.out.println("linkHashSet----------" + linkHashSet);

        //内部实现排序
        System.out.println("treeSet---------------" + treeSet);


    }


    @Test
    public void testTreeSet() {

        TreeSet<Student> treePeople = new TreeSet<>();

        Student student1 = new Student("zhangsan", 15);
        Student student2 = new Student("lisi", 366);
        Student student3 = new Student("wangwu", 18);
        Student student4 = new Student("dede", 45);
        Student student5 = new Student("io", 28);

        treePeople.add(student1);
        treePeople.add(student2);
        treePeople.add(student3);
        treePeople.add(student4);
        treePeople.add(student5);


        for (Student s : treePeople) {

            System.out.println(s);

        }


    }


    @Test
    public void testSuanfa() {


        int i = 1;
        int a = 0;
        System.out.println("a=i++===>  " + (a = i++));//1
        //System.out.println("a=++i===>  "+(a=++i));//2
    }


    @Test
    public void test56() {

        ArrayList<People> list = new ArrayList<>();


        var People1 = new People("现金提现", 3);
        var People2 = new People("现金提现", 1);
        var People3 = new People("现金提现", 2);
        var People4 = new People("现金提现", 2);
        var People5 = new People("游戏人物", 2);
        var People6 = new People("游戏人物", 2);
        var People7 = new People("游戏人物", 2);


        list.add(People1);
        list.add(People2);
        list.add(People3);
        list.add(People4);
        list.add(People5);
        list.add(People6);
        list.add(People7);


        ArrayList<People> list1 = new ArrayList<>();
        ArrayList<People> list2 = new ArrayList<>();


        int i = 2;
        int j = 1;
        for (People o : list) {
            if (list.size() <= i && "现金提现".equals(o.getName())) {
                var People8 = new People();
                People8.setAge(o.getAge());
                People8.setName(o.getName());
                list1.add(People8);
            }
        }

        System.out.println("集合list1***********" + list1);


        for (People k : list) {
            if (list.size() <= j && "游戏人物".equals(k.getName())) {
                var People9 = new People();
                People9.setAge(k.getAge());
                People9.setName(k.getName());
                list2.add(People9);
            }


        }

        System.out.println("集合list1***********" + list2);

        list1.addAll(list2);

//        Collections.sort(list1, new Comparator<People>() {
//            @Override
//            public int compare(People o1, People o2) {
//                //降序
//                return o2.getAge().compareTo(o1.getAge());
//            }
//        });

        System.out.println(list1);


    }


    @Test
    public void title_001() throws Exception {

        System.out.println("执行开始------..........000");
        Thread thread = new Thread();
        thread.setName("线程 B");
        thread.join();

        System.out.println("执行结束-----------惆怅长岑长错错错错错----");


    }


    @Test
    public void testStreamxiaoLv() {

        List<String> stringList = new ArrayList<>();

        long start = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            stringList.add("测试数据：ID" + UUID.randomUUID().toString());
        }

        long costTime = System.currentTimeMillis() - start;

        System.out.println("for 执行完毕 添加数据20w, 总耗时为： " + costTime);


        stringList.stream().forEach(s -> {
            System.out.println(s);
        });


    }

    @Test
    public void TwinsLockTest() {

        final Lock lock = new TwinsLock();
        class Worker extends Thread {
            public void run() {
                while (true) {
                    lock.lock();
                    try {
                        try {
                            TimeUnit.SECONDS.sleep(1);
                            System.out.println(Thread.currentThread().getName());
                            TimeUnit.SECONDS.sleep(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    } finally {
                        lock.unlock();
                    }
                }
            }
        }
// 启动10个线程
        for (int i = 0; i < 10; i++) {
            Worker w = new Worker();
            w.setDaemon(true);
            w.start();
        }
// 每隔1秒换行
        for (int i = 0; i < 10; i++) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println();
        }
    }


    @Test
    public void test633(){
        StateType distributionGoodsService = distributeSimpleFactory.getDistributionGoodsService(3);
        String s = distributionGoodsService.jiaoValue(3);
        System.out.println(s);



    }

    @Test
    public  void test668(){
        Admin admin = new Admin();
        ConfigOriginator configOriginator = new ConfigOriginator();

//        "1000001", "配置内容A=哈
//        哈", new Date(), "⼩傅哥"
        configOriginator.setConfigFile(new ConfigFile("1000001","配置内容A=哈哈",new Date(),""));
                admin.append(configOriginator.saveMemento()); // 保存配置
        configOriginator.setConfigFile(new ConfigFile("1000002", "配置内容A=嘻嘻", new Date(), "⼩傅哥"));
                admin.append(configOriginator.saveMemento()); // 保存配置
        configOriginator.setConfigFile(new ConfigFile("1000003", "配置内容A=么 么", new Date(), "⼩傅哥"));
                admin.append(configOriginator.saveMemento()); // 保存配置
        configOriginator.setConfigFile(new ConfigFile("1000004", "配置内容A=嘿嘿", new Date(), "⼩傅哥"));
                admin.append(configOriginator.saveMemento()); // 保存配置
        // 历史配置(回滚)
        configOriginator.getMemento(admin.undo());
        log.info("历史配置(回滚)undo：{}", JSON.toJSONString(configOriginator.getConfigFile()));
        // 历史配置(回滚)
        configOriginator.getMemento(admin.undo());
        log.info("历史配置(回滚)undo：{}",
                JSON.toJSONString(configOriginator.getConfigFile()));
        // 历史配置(前进)
        configOriginator.getMemento(admin.redo());
        log.info("历史配置(前进)redo：{}",
                JSON.toJSONString(configOriginator.getConfigFile()));
        // 历史配置(获取)
        configOriginator.getMemento(admin.get("1000002"));
        log.info("历史配置(获取)get：{}",
                JSON.toJSONString(configOriginator.getConfigFile()));
    }


}










